'use client';

import { useState, useRef, useCallback } from 'react';
import { useTTS } from '@/lib/hooks/useAI';

interface VoicePlayerProps {
  text: string;
  voice?: string;
  disabled?: boolean;
  className?: string;
}

export function VoicePlayer({ 
  text, 
  voice = '21m00Tcm4TlvDq8ikWAM',
  disabled = false, 
  className = "" 
}: VoicePlayerProps) {
  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef<HTMLAudioElement>(null);
  
  const { textToSpeech, loading: ttsLoading } = useTTS();

  const stopCurrentAudio = useCallback(() => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
  }, []);

  const playAudio = useCallback(async () => {
    if (!text.trim()) return;

    try {
      // Stop any currently playing audio
      stopCurrentAudio();

      // Get language settings
      const language = localStorage.getItem('preferredLanguage') || 'en';

      // Always generate new audio with current voice settings
      const result = await textToSpeech({
        text,
        voice,
        format: 'mp3',
        language
      });
      
      // Create new audio element and play
      const audio = new Audio(result.audioUrl);
      audioRef.current = audio;
      
      audio.onplay = () => setIsPlaying(true);
      audio.onended = () => setIsPlaying(false);
      audio.onerror = () => {
        setIsPlaying(false);
        console.error('Audio playback failed');
      };
      
      await audio.play();
      
    } catch (error) {
      console.error('Voice playback failed:', error);
      setIsPlaying(false);
    }
  }, [text, voice, textToSpeech, stopCurrentAudio]);

  const stopAudio = useCallback(() => {
    stopCurrentAudio();
    setIsPlaying(false);
  }, [stopCurrentAudio]);

  return (
    <div className={`flex items-center gap-2 ${className}`}>
      <button
        onClick={isPlaying ? stopAudio : playAudio}
        disabled={disabled || ttsLoading || !text.trim()}
        className={`
          flex items-center justify-center w-8 h-8 rounded-full transition-all duration-200 shadow-sm
          ${isPlaying 
            ? 'bg-red-500 hover:bg-red-600 text-white scale-105' 
            : 'bg-emerald-500 hover:bg-emerald-600 text-white hover:scale-105'
          }
          ${disabled || ttsLoading || !text.trim() ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
        `}
        title={isPlaying ? 'Stop Playback' : 'Play Voice'}
      >
        {ttsLoading ? (
          <div className="w-3 h-3 border-2 border-white border-t-transparent rounded-full animate-spin" />
        ) : isPlaying ? (
          <div className="w-2 h-2 bg-white rounded-sm" />
        ) : (
          <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.617.792L4.617 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.617l3.766-3.792a1 1 0 011.617.792zM14.657 2.929a1 1 0 011.414 0A9.972 9.972 0 0119 10a9.972 9.972 0 01-2.929 7.071 1 1 0 01-1.414-1.414A7.971 7.971 0 0017 10c0-2.21-.894-4.208-2.343-5.657a1 1 0 010-1.414zm-2.829 2.828a1 1 0 011.415 0A5.983 5.983 0 0115 10a5.984 5.984 0 01-1.757 4.243 1 1 0 01-1.415-1.415A3.984 3.984 0 0013 10a3.983 3.983 0 00-1.172-2.828 1 1 0 010-1.415z" clipRule="evenodd" />
          </svg>
        )}
      </button>
    </div>
  );
}